package com.dotflat.xj.service.impl;

import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.dotflat.util.AssertUtil;
import com.dotflat.xj.domain.Data;
import com.dotflat.xj.po.DataPO;
import com.dotflat.xj.repository.DataRepository;
import com.dotflat.xj.service.DataService;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.CopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class DataServiceImpl extends AreableObjectBaseServiceImpl<Data, DataRepository> implements DataService {

    @Autowired
    @Override
    public void setBaseRepository(DataRepository repository){
        super.setBaseRepository(repository);
    }

    @Autowired
    private  DataRepository dataRepository;

    @Autowired
    protected MemVerificationCache cache;


    @Override
    public DataPO addData(Data data) {
        DataPO dataPO = new DataPO();
        Data data1 =  dataRepository.save(data);
        CopyUtils.copyProperties(data1 , dataPO);
        return dataPO;
    }

    @Override
    public List<Data> findAllByType(String type) {
        return dataRepository.findAllByType(type);
    }

    @Override
    public List<Data> typeByData(String type,String areaId) {
        return dataRepository.typeByData(type, areaId);
    }

    @Override
    public List<Data> findAllByTypeAndAreaIdAndLabel(String type, String areaId, String label) {
        return dataRepository.findAllByTypeAndAreaIdAndLabel(type,areaId,label);
    }


    @Override
    public List<Data> findAllByTypeAndAreaId(String type, String areaId) {
        return dataRepository.findAllByTypeAndAreaId(type,areaId);
    }
    @Override
    public Data getData(String id) {
        return dataRepository.getOne(id);
    }

    @Override
    public Data update(String ticket,String id, String val) {
        StaffDTO staff = cache.getStaff(ticket);
        if (AssertUtil.isEmpty(staff)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        Data data = dataRepository.getOne(id);
        if (AssertUtil.isEmpty(data)){
            throw   new BusinessException(ErrorCode.UNDEFINED, "id错误");
        }
        data.setAreaId(staff.getAreaId());
        data.setCreatedBy(staff.getId());
        data.setVal(val);
        dataRepository.save(data);
        return data;
    }
}